import { APP_MODE, lazy, type IRouterConfig } from 'ice';

import { AuthRouter } from './Auth';
import Login from '@/modules/Login';
import ErrorPage from './components/ErrorPage';
import Index from '@/layout';

import { flatJSONTree } from './utils/json';

// 构造动态路由
const Title = 'XXX';
const NotFoundRoute = { path: '*', component: ErrorPage };

const DynamicRoutes: IRouterConfig[] = [];
const ExtDynamicRoutes: IRouterConfig[] = [];
const routeArr = flatJSONTree(window.SceneConfig, true);

for (let i = 0; i < routeArr.length; i++) {
  const item = routeArr[i];

  // 常规路由
  if (!item.children || item.isRoute) {
    // 去除掉中间的多余的路径，只保留首位（避免文件目录的多层嵌套）
    let { path } = item;
    const arr = path.split('/');
    if (arr.length > 2) path = `${arr.shift()}/${arr.pop()}`;

    const route: IRouterConfig = {
      path: item.path,
      component: lazy(() => import(`@/modules/${path}/index.tsx`)),
      exact: true,
      getInitialProps: () => ({ _meta: item, ...item.props }),
      pageConfig: {
        title: `${Title} ${item.title}`, // 每个页面单独的title
        // auth: [item.path], // 屏蔽鉴权，有需要的时候放开页面鉴权
      },
    };

    if (item.isBlank) ExtDynamicRoutes.push(route);
    else DynamicRoutes.push(route);
  }
}

// 完整的路由
const routes: IRouterConfig[] = [
  {
    path: '/',
    component: AuthRouter,
    children: [
      // 登录
      {
        path: '/login',
        component: Login,
        exact: true,
        pageConfig: {
          title: `${Title} 登录页`,
        },
      },
      {
        path: '/',
        exact: true,
        redirect: DynamicRoutes[0].path,
      },

      // 其他布局的路由（大屏）
      ...ExtDynamicRoutes,

      // 动态路由
      {
        path: '/',
        component: Index,
        children: DynamicRoutes.concat([NotFoundRoute]),
        pageConfig: {
          title: `${Title} 后台管理`,
        },
      },
      NotFoundRoute,
    ],
  },
];

export default routes;
